<template>
  <div>
    <div class="card"
      style="margin-bottom: 10px;background: linear-gradient(to bottom, #f5f3f2, #92bdce);border: 1px solid;">
      <el-input v-model="data.name" style="width: 240px; margin-right: 10px" placeholder="请输入专业查询"
        :prefix-icon="Search"></el-input>
      <el-input v-model="data.description" style="width: 240px; margin-right: 10px" placeholder="请输入描述查询"
        :prefix-icon="Search"></el-input>
      <el-button type="primary" @click="load">查询</el-button>
      <el-button type="info" style="margin: 0 10px" @click="reset">重置</el-button>
    </div>

    <div class="card"
      style="margin-bottom: 10px;background: linear-gradient(to bottom, #f5f3f2, #92bdce);border: 1px solid;">
      <div style="margin-bottom: 10px">
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <el-button type="danger" style="margin-left: 10px" @click="delBatch">批量删除</el-button>
        <el-button type="info" style="margin-left: 10px">导 入</el-button>
        <el-button type="success" style="margin-left: 10px">导 出</el-button>
      </div>
      <el-table :data="data.tableData" stripe>
        <el-table-column type="selection" width="55" />
        <el-table-column label="编号" prop="specialityId"></el-table-column>
        <el-table-column label="专业" prop="name"></el-table-column>
        <el-table-column label="描述" prop="description"></el-table-column>

        <el-table-column label="操作" align="center" width="160">
          <template #default="scope">
            <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" @click="handleDelete(scope.row.specialityId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="card" style="background: linear-gradient(to bottom, #f5f3f2, #92bdce);border: 1px solid;">
      <el-pagination @current-change="load" @size-change="load" v-model:current-page="data.pageNum"
        v-model:page-size="data.pageSize" :page-sizes="[5, 10, 15, 20]" layout="total, sizes, prev, pager, next, jumper"
        :total="data.total" />
    </div>

    <el-dialog title="新增专业信息" width="600" v-model="data.formVisible" :close-on-click-modal="false" destroy-on-close>
      <el-form :model="data.form" label-width="100px" style="padding: 20px 25px 0px 0px" ref="formRef"
        :rules="data.rules">
        <el-form-item label="专业名称" prop="name">
          <el-input v-model="data.form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="专业描述" prop="description">
          <el-input v-model="data.form.description" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="data.formVisible = false">取 消</el-button>
        <el-button type="primary" @click="save()">添 加</el-button>
      </template>
    </el-dialog>

    <el-dialog title="修改专业信息" width="600" v-model="data.editForm" :close-on-click-modal="false" destroy-on-close>
      <el-form :model="data.form" style="padding: 20px 35px 0px 0px" label-width="120px" ref="formRef02"
        :rules="data.rules02">
        <el-form-item label="专业名称" prop="name">
          <el-input v-model="data.form.name" placeholder="请输入修改后的专业名称" />
        </el-form-item>
        <el-form-item label="专业描述" prop="description">
          <el-input v-model="data.form.description" placeholder="请输入修改后的专业描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeDialog()">取 消</el-button>
        <el-button type="primary" @click="update()">保 存</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import alovaInstance from "@/utils/request";
import { ElMessage, ElMessageBox } from "element-plus";
import { addSpeciality, deleteSpeciality, updateSpeciality } from "@/api/college_admin/college";
import { Search } from "@element-plus/icons-vue";

const data = reactive({
  user: JSON.parse(localStorage.getItem('credit-system-user') || '{}'),
  pageNum: 1,
  pageSize: 5,
  total: 0,
  formVisible: false,
  editForm: false,
  form: {},
  tableData: [],
  title: '',
  name: '',
  description: '',
  rules: {
    name: [
      { required: true, message: '请输入专业', trigger: 'blur' }
    ],
    description: [
      { required: true, message: '请输入专业描述', trigger: 'blur' }
    ]
  },
  rules02: {
    name: [
      { required: true, message: '请输入专业名称', trigger: 'blur' }
    ],
    description: [
      { required: true, message: '请输入专业描述', trigger: 'blur' }
    ]
  }
})
const formRef = ref();
const formRef02 = ref();

data.form.updateBy = data.user.adminId

const load = () => {
  alovaInstance.Get('/collegeAdminSpeciality/selectSpeciality', {
    params: {
      page: data.pageNum,
      size: data.pageSize,
      collegeId: data.user.collegeId,
      name: data.name,
      description: data.description
    }
  }).then(res => {
    console.log(res);

    if (res.code === '200') {
      data.tableData = res.data?.list
      data.total = res.data?.total
    }
  }).catch(error => {
    console.error('请求失败:', error);
    ElMessage.error(error.message);
  });

}

// 新增
const handleAdd = () => {
  data.form = {}
  data.form.createBy = data.user.username
  data.form.collegeId = data.user.collegeId
  data.formVisible = true
}
// 编辑
const handleEdit = (row) => {
  data.form = { ...row };
  data.editForm = true
}

const closeDialog = () => {
  data.form = {}
  data.editForm = false
}


//新增方法
const save = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      const formData = data.form;
      addSpeciality(formData).then((res) => {
        if (res.code === '200') {
          ElMessage.success('新增成功')
          data.formVisible = false
          setTimeout(() => { location.reload(); }, 500);
        }
      }).catch(error => {
        console.error('请求失败:', error);
        ElMessage.error(error.message);
        /*data.formVisible = false*/
      });
    }
  })
}

//修改信息
const update = () => {
  formRef02.value.validate((valid) => {
    if (valid) {
      const formData = data.form;
      console.log(formData);
      updateSpeciality(formData).then((res) => {
        if (res.code === '200') {
          ElMessage.success('修改成功');
          data.formVisible = false
          setTimeout(() => { location.reload(); }, 500);
        }
      }).catch(error => {
        console.error('请求失败:', error);
        ElMessage.error(error.message);
        /*data.formVisible = false*/
      });
    }
  })
}

// 删除
const handleDelete = (id) => {
  ElMessageBox.confirm('确定要删除该记录吗？此操作不可撤销！', '删除确认', {
    confirmButtonText: '确认删除',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteSpeciality(id, data.user.username).then(() => {
      ElMessage.success('删除成功');
      location.reload();
    }).catch(err => {
      ElMessage.error('删除失败：' + err.message);
    });
  })
    .catch(() => {
      // 用户点击取消，无需执行操作
    });
}

// 重置
const reset = () => {
  data.name = ''
  data.description = ''
  load()
}

load()
</script>

<style lang="scss" scoped></style>